package com.shf.job;

import com.shf.domain.entity.Article;
import com.shf.service.ArticleService;
import com.shf.util.RedisCache;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/** 定时任务 同步数据库数据
 * @author 叶枫
 * @date 2023/11/13.
 */

@Component
public class ViewCountJob {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleService articleService;

//每隔3分钟，把redis的浏览量数据更新到mysql数据库
    @Scheduled(cron = "0/55 * * * * ?")
    public void updateViewCount(){
        //获取 redis的数据
        Map<String, Integer> cacheMap = redisCache.getCacheMap("viewCount");

        List<Article> collect = cacheMap.entrySet()
                .stream()
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());

        //更新到数据库中
        articleService.updateBatchById(collect);


    }
}
